<!-- Carousel.vue -->
<template>
  <!-- 轮播容器 -->
  <div class="overflow-hidden absolute w-full h-full top-0 left-0">
    <!-- 轮播轨道 -->
    <div ref="carouselTrack" class=" carousel-track absolute inset-0 w-full h-full transition-all transform ease-in-out" :style="{ transform: `translateX(-${currentSlide * slideWidth}px)` }">
      <slot :image="images[currentSlide]"></slot> <!-- 子组件插入点，用于放置轮播项 -->
    </div>
  </div>
  <!-- 左右切换按钮 -->
  <button v-if="images.length > 1" @click="prevSlide()" class="hidden sm:block carousel-control-left absolute top-1/2 left-0 -translate-y-1/2 rounded-full bg-gray-200 hover:bg-gray-300 p-2 text-gray-700 focus:outline-none">
    <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
    </svg>
  </button>
  <button v-if="images.length > 1" @click="nextSlide()" class="hidden sm:block carousel-control-right absolute top-1/2 right-0 -translate-y-1/2 rounded-full bg-gray-200 hover:bg-gray-300 p-2 text-gray-700 focus:outline-none">
    <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
    </svg>
  </button>
  <div v-if="images.length > 1" class="carousel-indicators absolute bottom-2 left-[50%] -translate-x-[50%] trans flex justify-center space-x-2">
    <button
      v-for="(image, index) in images"
      :key="index"
      :class="{ 'bg-white opacity-50 ring-2 ring-offset-2 ring-gray-300': index !== currentSlide, 'bg-blue-500 opacity-100 ring-blue-500': index === currentSlide }"
      @click="goToSlide(index)"
      class="w-3 h-3 rounded-full cursor-pointer focus:outline-none"
    ></button>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue';

const props = defineProps({
  images: {
    type: Array,
    required: true,
  },
  interval: {
    type: Number,
    default: 5000,
  },
});
const currentSlide = ref(0);
const slideWidth = ref(0);
let carouselTrack = ref(null)
let timer = null;
let goToSlide = (index) => {
  currentSlide.value = index;
}
onMounted(() => {
  slideWidth.value = carouselTrack.value.offsetWidth;
  startAutoSlide();
});

onBeforeUnmount(() => {
  clearTimeout(timer);
});

function prevSlide() {
  if (currentSlide.value > 0) {
    goToSlide(currentSlide.value - 1);
  }
}

function nextSlide() {
  if (currentSlide.value < props.images.length - 1) {
    goToSlide(currentSlide.value + 1);
  }
}

function startAutoSlide() {
  timer = setTimeout(() => {
    nextSlide();
    startAutoSlide();
  }, props.interval);
}
</script>